package com.example.exception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ScriptExecutor {
    public String executeScript(String scriptPath) {
        ProcessBuilder processBuilder = new ProcessBuilder("python", scriptPath);
        processBuilder.redirectErrorStream(true); // 合并标准输出和错误输出

        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                return "脚本执行成功\n输出内容如下:\n" + output.toString();
            } else {
                return "脚本执行失败\n错误输出如下:\n" + output.toString();
            }
        } catch (IOException | InterruptedException e) {
            return "执行脚本时发生错误: " + e.getMessage();
        }
    }
}
